<?php
/**
 * User: @lixu
 * Date: 2019-05-29
 * Time: 15:10
 */

namespace Biz\service\wiki;

use Biz\cache\wiki\CategoryWiki;
use Biz\model\Album\AlbumTagClassifyMappingModel;
use Biz\model\brand\Brand;
use Biz\model\CategoryWikiCard as mCategoryWikiCard;
use Biz\model\ShopCategoryClassify as mShopCategoryClassify;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\service\Album\AlbumListService;
use Biz\service\ShopClassify;
use Doraemon\cache\WikiRanking\GoodsChannelWikiRanking;
use Doraemon\model\Elasticsearch\EsWikiListModel;
use Doraemon\model\Es\WikiBasic as esWikiBasic;
use Doraemon\service\Elasticsearch\EsAlbumService;
use Doraemon\service\statSign\Basic as basicStatSign;
use Doraemon\service\statSign\Basic as statSign;
use Doraemon\tools\BlockType;
use Doraemon\tools\HhzClient;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;

class ClassifyList
{
    const TAB_TYPE = 'classify_list';

    public static function getList($categoryId, $params, $sortType, $page, $uid, $currentTime = 0)
    {
        $list = [];

        if ($page > Schedule::SAVE_MAX_PAGE) {
            return ['is_over' => 1, 'list' => []];
        }

        $cateIds = [];
        $rankingCategoryId = 0;
        $insertWikiId = null;
        $insertWikiIdIndex = null;
        $classifyInfo = ShopClassify::quiltGetClassifyById($categoryId);
        if ($categoryId && $classifyInfo) {
            if (in_array($classifyInfo['deep'], [mShopCategoryClassify::DEEP_FIRST_CLASSIFY, mShopCategoryClassify::DEEP_SECOND_CLASSIFY, mShopCategoryClassify::DEEP_THIRD_CLAORCATE])) {
                $params = self::verifyParams($params);
                list($insertWikiIdIndex, $insertWikiId) = self::showTclGoods($page, $categoryId, $params);
                // 如果用户点击分类筛选的话，单独根据用户点击的分类筛选就ok  否则的话，就需要遍历出当前分类对应的三级分类
                if (isset($params['category'])) { //存在三级分类
                    foreach ($params['category'] as $paramsCategoryId) {
                        if (!$rankingCategoryId) {
                            $rankingCategoryId = $paramsCategoryId;
                        }
                        $classifyInfo = ShopClassify::quiltGetClassifyById($paramsCategoryId);
                        //三级分类
                        if (
                            ($classifyInfo['deep'] == mShopCategoryClassify::DEEP_THIRD_CLAORCATE) ||
                            ($classifyInfo['deep'] == mShopCategoryClassify::DEEP_SECOND_CLASSIFY && $paramsCategoryId == $categoryId)
                        ) {
                            $cateIds = array_merge($cateIds, array_column($classifyInfo['cate_list'], 'id'));
                        } else {
                            throw new \Exception('无效的三级分类');
                        }
                    }
                } else {
                    $rankingCategoryId = $categoryId;
                    if ($classifyInfo['deep'] == mShopCategoryClassify::DEEP_FIRST_CLASSIFY) {
                        $cateIds = [];
                        foreach ($classifyInfo['classifies'] as $secClassify) {
                            $cateIds = array_merge($cateIds, array_column($secClassify['cate_list'], 'id'));
                            foreach ($secClassify['classifies'] as $thirdClassify) {
                                $cateIds = array_merge($cateIds, array_column($thirdClassify['cate_list'], 'id'));
                            }
                        }
                    } else if ($classifyInfo['deep'] == mShopCategoryClassify::DEEP_SECOND_CLASSIFY) {
                        $cateIds = array_column($classifyInfo['cate_list'], 'id');
                        $thirdClassifies = [];
                        foreach ($classifyInfo['classifies'] as $classify) {
                            $cateIds = array_merge($cateIds, array_column($classify['cate_list'], 'id'));
                        }
                    } else if ($classifyInfo['deep'] == mShopCategoryClassify::DEEP_THIRD_CLAORCATE) {
                        $cateIds = array_column($classifyInfo['cate_list'], 'id');
                        $thirdClassifies = [];
                        foreach ($classifyInfo['classifies'] as $classify) {
                            $cateIds = array_merge($cateIds, array_column($classify['cate_list'], 'id'));
                        }
                    }
                }
//                if ($classifyInfo['deep'] == mShopCategoryClassify::DEEP_FIRST_CLASSIFY) {
//                    $wikiCard = self::getWikiCard($categoryId);
//                }

                // 获取到了cateIds 这个 id有可能是1234级分类的任何一类， 根据分类查询
                $where = [
                    'category_id' => implode(',', array_unique($cateIds)), //array_unique($cateIds)
                    'brand_id' => isset($params['brand']) ? $params['brand'] : 0,
                    'price_range' => $params['price_range'],
                    //'wiki_id' => array_column($wikiCard, 'wiki_id')
                ];

                // 只改热度排序 且时间戳有值的情况
                if ($currentTime && $sortType == Schedule::SORT_TYPE_HOT) {
                    Schedule::getCategoryLisyOrder($where, $currentTime);
                }

                $where = array_filter($where);

                if ($currentTime && $sortType == Schedule::SORT_TYPE_HOT) {
                    $result = Schedule::searchForCategoryLisy($where, $sortType, $page, $categoryId);
                } else {
//                   $result = esWiki::getList($where, esWiki::SCENES_APP_CATEGORY_LIST, $sortType, $page);
                    $result = EsWikiListModel::getList($where, EsWikiListModel::SCENES_APP_CATEGORY_LIST, $sortType, $page);
                }
            } else {
                Log::debug('无效的分类ID:' . $categoryId, $classifyInfo);
                throw new \Exception('无效的分类ID' . $categoryId);
            }

            $wikiIds = $result['rows'];

            $wikiIdList = []; // 初始化列表用的数组
//            if ($wikiCard) {
//                $wikiCard = array_column($wikiCard, null, 'insert_position');
//                // 按照后台设置的位置将数据插入数组(占位)
//                foreach (array_column($wikiCard, 'insert_position') as $index) {
//                    $wikiIdList[$index - 1] = $wikiCard[$index]['wiki_id'];
//                }
//            }

            // 遍历$wikiIds将其插入到数组，如果已经有数据(占位)占用了key的情况下，递归数组，直到找到可用的key
            if ($wikiIdList) {
                foreach ($wikiIds as $key => $id) {
                    $i = 0;
                    if (isset($wikiIdList[$key])) {
                        while (true) {
                            $i++;
                            if (!isset($wikiIdList[$i])) {
                                $wikiIdList[$i] = $id;
                                break;
                            }
                        }
                    } else {
                        $wikiIdList[$key] = $id;
                    }
                }
                ksort($wikiIdList);
            } else {
                $wikiIdList = $wikiIds;
            }
            if (!is_null($insertWikiId) && !is_null($insertWikiIdIndex)) {
                $wikiIdList[] = $insertWikiId;
            }
            $wikiIdList = array_unique($wikiIdList);
            $wikiList = Wiki::getWikiList($wikiIdList, $uid, Wiki::FIELDS_GROUP_MASONRY_LIST);

//            if (count($wikiList) > 3) {
//                $thirdCategoryList = [
//                    'type' => 2,
//                    'type_desc' => '三级分类',
//                    'classifies' => self::getThirdCategoryList($classifyInfo)
//                ];
//            }

            $i = 0;
            $insertWikiInfo = [];
            foreach ($wikiList as $value) {
                ++$i;

                $statSign = basicStatSign::genStatSign(basicStatSign::MODULE_CLASSIFY_LIST_WIKI_LIST, [
                    basicStatSign::EXTEND_KEY_OBJ_ID => $value['basic_id'],
                    basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI_BASIC,
                ], ['category_id' => $categoryId]);

                $value["statSign"] = $statSign;
                $formatData = [
                    'type' => 1,
                    'type_desc' => '商品',
                    'wiki_info' => $value,
                    'statSign' => $statSign,
                ];

                if (!is_null($insertWikiId) && !is_null($insertWikiIdIndex) && $value['id'] == $insertWikiId) {
                    $insertWikiInfo = $formatData;
                } else {
                    $list[] = $formatData;
                }

//                if ($i == 4 && $page == 1 && $thirdCategoryList['classifies']) {
//                    array_push($list, $thirdCategoryList);
//                }

            }

            // 临时代码 过滤同名的内容
            $uniqueBasicIds = array();

            foreach ($list as $itemKey => $item) {
                if (isset($item["wiki_info"]) && isset($item["wiki_info"]["basic_id"]) && $item["wiki_info"]["basic_id"] && !in_array($item["wiki_info"]["basic_id"], $uniqueBasicIds)) {
                    array_push($uniqueBasicIds, $item["wiki_info"]["basic_id"]);
                } else {
                    unset($list[$itemKey]);
                }
            }

            $rankingCategoryId = $rankingCategoryId ?? $categoryId;
            // 插入榜单卡片
            self::insertWikiRankingCard($rankingCategoryId, $page, $list);
            //插入优先推荐精选清单，每10个卡片插1个清单卡片，按生产时间倒序
            if (version_compare(HhzClient::getClientVersion(), "6.9.0", ">=")) {
                self::insertWikiAlbumCard($rankingCategoryId, $page, $list);
            }
            if (!is_null($insertWikiId) && !is_null($insertWikiIdIndex) && $insertWikiInfo) {
                array_splice($list, $insertWikiIdIndex, 0, [$insertWikiInfo]);
            }

            $list = self::formatList(array_filter($list));

            return ['is_over' => $result['is_over'], 'list' => $list];

        }
        return ['is_over' => 1, 'list' => []];
    }

    private static function formatList($list)
    {
        $result = [];
        foreach ($list as $row) {
            if (isset($row['type']) && $row['type'] == 1) {
                unset($row['wiki_info']['statSign']);
                $info = [
                    'type' => BlockType::TYPE_WIKI,
                    'wiki' => $row['wiki_info'],
                    'statSign' => $row['statSign']
                ];
            } else if (isset($row['type']) && $row['type'] == 1300) {
                $info = $row;
            } else if (isset($row['type']) && $row['type'] == BlockType::TYPE_WIKI_ALBUM) {
                $info = $row;
            }
            $result[] = $info;
        }
        return $result;

    }

    // 插入榜单卡片
    public static function insertWikiRankingCard($categoryId, $page, &$list)
    {
        $start = $page - 1;
        $end = $start;
        $rankingId = GoodsChannelWikiRanking::getList($categoryId, $start, $end);

        if (is_array($rankingId) && $rankingId) {
            $RankingCards = \Biz\service\wikiRanking\Ranking::multiFormatRankingCard($rankingId);
//            $RankingCards = \Biz\service\wikiRanking\Ranking::multiFormatRankingCard($rankingId);

            if (is_array($RankingCards) && $RankingCards) {
                $RankingCard = array_shift($RankingCards);
                $formatRankingCard = array(
                    "type" => BlockType::TYPE_RANKING,
                    "ranking" => array(
                        "ranking_info" => $RankingCard
                    ),
                    "statSign" => statSign::genStatSign(statSign::MODULE_SEARCH_RESULT_RANKING, [
                        statSign::EXTEND_KEY_OBJ_ID => array_shift($rankingId),
                        statSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_RANKING,
                        statSign::EXTEND_KEY_FROM => "classify"
                    ], [
                        "ranking_id" => array_shift($rankingId),
                        "uid" => HhzClient::getUid(),
                    ])
                );

                $index = rand(0, 9);
                $list = \Doraemon\service\search\Schedule::insertContent($formatRankingCard, $list, $index);
            }
        }
    }

    /**
     * @param $categoryId
     * @param $page
     * @param $list
     */
    public static function insertWikiAlbumCard($categoryId, $page, &$list)
    {
        //根据分类id  查询关联的清单标签
        $tags = AlbumTagClassifyMappingModel::selectByWhere(['status' => AlbumTagClassifyMappingModel::STATUS_NORMAL, 'classify_id' => $categoryId], 'tag');
        if (!empty($tags)) {
            //es 根据指定条件过滤清单 并返回结果
            $data = (new EsAlbumService)->getByTags($tags, $page);
            $albumIdArr = [];
            if (isset($data['list']) && !empty($data['list'])) {
                $albumIdArr = array_column($data['list'], 'album_id');
            }
            $albumInfo = AlbumListService::getAlbumListByAlbumIds($albumIdArr);
            if ($albumInfo) {
                foreach ($albumInfo as $key => $val) {
                    $val['statSign'] = basicStatSign::genStatSign(basicStatSign::MODULE_CLASSIFY_LIST_ALBUM_LIST, [
                        basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_WIKI_ALBUM,
                        basicStatSign::EXTEND_KEY_OBJ_ID => $val['album_info']['album_id'],
                        basicStatSign::EXTEND_KEY_INDEX => $key,
                    ], [
                        'category_id' => $categoryId,
                    ]);
                    $res[] = $val;
                }
                $list = \Doraemon\service\search\Schedule::insertContent($res[0] ?? [], $list, 10);
                $list = \Doraemon\service\search\Schedule::insertContent($res[1] ?? [], $list, 30);
            }
        }


    }

    /**
     * 获取三级分类列表
     * @param $classifyInfo
     * @return array
     * @throws \Exception
     */
    private static function getThirdCategoryList($classifyInfo)
    {
        $thirdCategoryList = [];
        if ($classifyInfo['deep'] == mShopCategoryClassify::DEEP_SECOND_CLASSIFY || $classifyInfo['deep'] == mShopCategoryClassify::DEEP_THIRD_CLAORCATE) {
            if ($classifyInfo['classifies']) {
                foreach ($classifyInfo['classifies'] as $thirdClassifyId => $classify) {
                    if (count($thirdCategoryList) >= 4) {
                        break;
                    }

                    $thirdCategoryList[] = [
                        'id' => $classify['id'],
                        'title' => $classify['classify_name'],
                        "icon" => $classify['icon'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $classify['icon'], ImgUrl::IMAGE_SIZE_OP_ORI) : '',
                    ];
                }
            }
        }

        return $thirdCategoryList;
    }

    private static function verifyParams($params)
    {

        $result = [];
        if ($params) {

            $params = json_decode($params, true);

            foreach ($params as $param) {
                if ($param['type'] == 'price_range') {
                    $result['price_range'] = array_column($param['list'], 'title');
                    if (!array_filter($result['price_range'])) {
                        unset($result['price_range']);
                    } else {
                        sort($result['price_range']);
                    }

                } else if ($param['type'] == 'category') {
                    $result['category'] = array_column($param['list'], 'id');
                    if (!array_filter($result['category'])) {
                        unset($result['category']);
                    }
                } else if ($param['type'] == 'brand') {
                    $result['brand'] = array_column($param['list'], 'id');
                    if (!array_filter($result['brand'])) {
                        unset($result['brand']);
                    }
                }
            }

        }

        return $result;
    }

    private static function getWikiCard($categoryId)
    {
        $nowTime = date('Y-m-d H:i:s');
        $where = [
            'category_id' => $categoryId,
            'card_status' => mCategoryWikiCard::STATUS_NORMAL,
        ];

        $wikiCard = mCategoryWikiCard::getListByWhere($where, [], ['insert_position' => 'ASC']);

        foreach ($wikiCard as $key => $value) {
            if (!($value['start_time'] <= $nowTime && $value['end_time'] >= $nowTime)) {
                unset($wikiCard[$key]);
            }
        }

        if ($wikiCard) {
            return $wikiCard;
        }

        return [];
    }

    /*category 卡片  双列瀑布流使用
     *
     * */
    public static function formateMultiCategoryIds($cate_ids = [])
    {
        $formate_list = [];
        //获取wiki信息
        if (empty($cate_ids)) return [];
        $classify_list = mShopCategoryClassify::selectInfos([
            'id' => $cate_ids,
            'status' => [
                mShopCategoryClassify::STATUS_NORMAL,
                mShopCategoryClassify::STATUS_HIDE
            ]

        ]);
        if ($classify_list && is_array($classify_list)) {
            foreach ($classify_list as $val) {
                $wiki_info = CategoryWiki::getWikiInfoByCateId($val['id']);
                if (empty($wiki_info)) continue;
                $link = \Doraemon\tools\LinkFormat::generateLink(\Doraemon\pockets\constInterface\LinkConf::LINK_APP_CATEGORIES_DETAIL, [
                    'category_id' => $val['parent_id'],
                    'sub_category_id' => $val['id']
                ]);
                if ($wiki_info['wiki_img_url']) {
                    $formate_list[$val['id']] = [
                        'category_info' => [
                            'id' => $val['id'],
                            'name' => $val['classify_name'],
                            'icon' => $val['icon_url'],
                            'recommendation' => "住友为你推荐<em>" . $wiki_info['count'] . "</em>" . $val['classify_name'],
                            'wiki_img_url' => $wiki_info['wiki_img_url'] ?: '',
                            'link' => $link['app_template'] ?? ''
                        ]
                    ];
                }
            }
        }
        return $formate_list;
    }

    /*获取商品信息 通过 cate_id
       *
       * */
    public static function setWikiInfoByCateId($cate_id)
    {
        try {
            $count = 0;
            $hot_wiki_img_url = '';
//            $cate_ids = CategoryClassify::getCategoryRelation($cate_id) ?: '';
            $redis = new \Hhz\Redis\newCache(\hhz\constant\redis\redisKeys::KEY_B_CACHE_CATEGORY_CLASSIFY_);
            $cate_ids = $redis->getCache($cate_id);
            $cate_ids = !empty($cate_ids) ? explode(',', $cate_ids) : [];
            if ($cate_ids) {
                $where = [];
                $where['OR'] = [
                    'second_category_id' => $cate_ids,
                    'third_category_id' => $cate_ids,
                    'four_category_id' => $cate_ids,
                ];
                $where['AND'] = [
                    'basic_state[!]' => mWikiBasic::STATE_DEL
                ];
                $count = mWikiBasic::selectCountWhere($where);
                $info = esWikiBasic::searchGetCategoryCard($cate_ids, [Brand::BRAND_TYPE_SUPER, Brand::BRAND_TYPE_BEST, Brand::BRAND_TYPE_COMMON, Brand::BRAND_TYPE_EXPIRE]);
                if ($info['cover_img']) {
                    $hot_wiki_img_url = $info['cover_img'];
                }
            }
            $data = [
                'count' => $count ?: 0,
                'wiki_img_url' => $hot_wiki_img_url
            ];
            CategoryWiki::setWikiInfoByCateId($cate_id, $data);
        } catch (\Exception $e) {
        }
    }

    private static function showTclGoods($page, $categoryId, $categoryParams)
    {
        $today = (int)date('Ymd');
        if (1 == $page) {
            if ($today >= 20231013 && $today <= 20231231) {
                $config = [
                    536 => ['id' => 2256, 'indexWikiId' => 297375], // 生活家电-空调-信息流1
                ];
                if ($config[$categoryId]) {
                    return self::showTclGoodsByCateAndId($config[$categoryId], $categoryParams);
                }
            }

            if ($today >= 20231120 && $today <= 20231126) {
                $config = [
                    530 => ['id' => 0, 'indexWikiId' => 303564], // 全部
                    1848 => ['id' => 2222, 'indexWikiId' => 296925], // 厨房大电-冰箱-信息流1
                    1796 => ['id' => 2273, 'indexWikiId' => 301815], // 卫浴电器-洗衣机-信息流1
                    1771 => ['id' => 2286, 'indexWikiId' => 303564], // 数码影音-电视机-信息流1
                ];
                if ($config[$categoryId]) {
                    return self::showTclGoodsByCateAndId($config[$categoryId], $categoryParams);
                }
            }

            if ($today >= 20231127 && $today <= 20231203) {
                $config = [
                    530 => ['id' => 0, 'indexWikiId' => 301815], // 全部
                    1848 => ['id' => 2222, 'indexWikiId' => 296925], // 厨房大电-冰箱-信息流1
                    1796 => ['id' => 2273, 'indexWikiId' => 301815], // 卫浴电器-洗衣机-信息流1
                    1771 => ['id' => 2286, 'indexWikiId' => 303564], // 数码影音-电视机-信息流1
                ];
                if ($config[$categoryId]) {
                    return self::showTclGoodsByCateAndId($config[$categoryId], $categoryParams);
                }
            }

            if ($today >= 20231204 && $today <= 20231210) {
                $config = [
                    530 => ['id' => 0, 'indexWikiId' => 297375], // 全部
                    1848 => ['id' => 2222, 'indexWikiId' => 296925], // 厨房大电-冰箱-信息流1
                    1796 => ['id' => 2273, 'indexWikiId' => 301815], // 卫浴电器-洗衣机-信息流1
                    1771 => ['id' => 2286, 'indexWikiId' => 303564], // 数码影音-电视机-信息流1
                ];
                if ($config[$categoryId]) {
                    return self::showTclGoodsByCateAndId($config[$categoryId], $categoryParams);
                }
            }

            if ($today >= 20231211 && $today <= 20231217) {
                $config = [
                    530 => ['id' => 0, 'indexWikiId' => 296925], // 全部
                    1848 => ['id' => 2222, 'indexWikiId' => 296925], // 厨房大电-冰箱-信息流1
                    1796 => ['id' => 2273, 'indexWikiId' => 301815], // 卫浴电器-洗衣机-信息流1
                    1771 => ['id' => 2286, 'indexWikiId' => 303564], // 数码影音-电视机-信息流1
                ];
                if ($config[$categoryId]) {
                    return self::showTclGoodsByCateAndId($config[$categoryId], $categoryParams);
                }
            }
        }

        return [null, null];
    }

    private static function showTclGoodsByCateAndId($value, $categoryParams)
    {
        $index = null;
        $indexWikiId = null;
        if ($categoryParams && $categoryParams['category']) {
            foreach ($categoryParams['category'] as $id) {
                if ($value['id'] == $id) {
                    $index = 0;
                    $indexWikiId = $value['indexWikiId'];
                }
            }
        } else {
            $index = 0;
            $indexWikiId = $value['indexWikiId'];
        }

        return [$index, $indexWikiId];
    }
}
